<template>
  <div class="container">
    <div>
      <el-row :gutter="1">
        <el-col :span="6">
          <el-form ref="form" :model="form" label-width="5.729vw">
            <el-form-item label="车辆名称：">
              <el-input
                v-model="select.LICENSE_PLATE"
                placeholder="请输入车辆名称"
                style="width: 250px"
              ></el-input>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="6">
          <el-form ref="form" :model="form" label-width="5.729vw">
            <el-form-item label="车辆所属公司：">
              <el-input
                v-model="select.COMPANY"
                placeholder="请输入车辆所属公司"
                style="width: 250px"
              ></el-input>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="6">
          <el-form ref="form" :model="form" style="float: right">
            <el-form-item>
              <el-button size="mini" type="primary" @click="screeningData"
                >查 询</el-button
              >
              <el-button size="mini" type="success" @click="handleAdd"
                >新 增</el-button
              >
              <el-button style="padding: 0; border: 0">
                <el-upload
                  action="/上传文件的接口"
                  :on-change="onChange"
                  :auto-upload="false"
                  :show-file-list="false"
                  accept=".xls, .xlsx"
                  class="upload"
                >
                  <el-button size="mini" type="success">导 入</el-button>
                </el-upload>
              </el-button>

              <!-- <el-button style="padding: 0; border: 0">
                <el-upload
                  action="/上传文件的接口"
                  :on-change="onChange"
                  :auto-upload="false"
                  :show-file-list="false"
                  accept=".xls, .xlsx"
                  class="upload"
                >
                  <el-button size="mini" type="success">导 入</el-button>
                </el-upload>
              </el-button> -->
              <el-button size="mini" type="warning" @click="exportExcel"
                >导 出</el-button
              >
              <!-- <el-button size="mini" type="success" @click="exportExcel">删 除</el-button> -->
              <!-- </el-form-item>
            <el-form-item> -->
              <!-- <el-form ref="form" :model="form" style="float:left"> -->
              <!-- <el-button size="mini" type="success" @click="exportExcel">导 入</el-button>
              <el-button size="mini" type="success" @click="exportExcel">导 出</el-button> -->
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
    <el-table
      highlight-current-row
      :data="
        tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)
      "
      border
    >
      <el-table-column
        prop="VID"
        label="ID"
        align="center"
        width="100"
      ></el-table-column>
      <el-table-column
        prop="COMPANY"
        label="车辆所属公司"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="LICENSE_PLATE"
        label="车辆名称"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="CAR_TYPE"
        label="车辆类型"
        align="center"
        width="100"
      ></el-table-column>
      <el-table-column
        prop="GPSValue"
        label="是否安装GPS"
        align="center"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="SIMCARD_NO"
        label="SIM卡号"
        align="center"
        width="150"
      ></el-table-column>
      <el-table-column
        prop="EOValue"
        label="是否安装视频"
        align="center"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="IdentificationCode"
        label="设备号"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="WEIGHT"
        label="载重"
        align="center"
        width="120"
      ></el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <!-- <el-button
            type="text"
            @click="handleDelete1(scope.$index, scope.row)"
            style="color: red"
            >删除</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="tableData.length"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      ></el-pagination>
    </div>
    <!-- 图片放大 -->
    <el-dialog
      title="图片展示"
      :visible.sync="showBigDialogVisible"
      width="30%"
    >
      <el-image style="width: 100%; height: 100%" :src="srcBig"></el-image>
    </el-dialog>
    <!-- 弹出框 -->
    <el-dialog
      :title="addDialogTitle"
      :visible.sync="isVisibleEdit"
      width="50%"
    >
      <el-form ref="form" :model="form" label-width="5.729vw" class="flex">
        <el-form-item
          label="车辆名称："
          class="wid50"
          v-if="this.addDialogTitle === '新增车辆基础信息'"
        >
          <el-input
            v-model="form.LICENSE_PLATE"
            placeholder="请输入车辆名称"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="车辆所属公司："
          class="wid50"
          v-if="this.addDialogTitle === '新增车辆基础信息'"
        >
          <el-select
            style="width: 15.625vw"
            v-model="form.CID"
            placeholder="请选择"
          >
            <el-option
              v-for="item in companyData"
              :key="item.CID"
              :label="item.CompanyName"
              :value="item.CID"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否安装GPS：" class="wid50">
          <el-select
            style="width: 15.625vw"
            v-model="form.IsSetupGPS"
            placeholder="请选择"
          >
            <el-option
              v-for="item in GPSlevel"
              :key="item.GPSlevelindex"
              :label="item.GPSleveltitle"
              :value="item.GPSlevelindex"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否安装视频：" class="wid50">
          <el-select
            style="width: 15.625vw"
            v-model="form.VIDEO"
            placeholder="请选择"
          >
            <el-option
              v-for="item in EOlevel"
              :key="item.EOlevelindex"
              :label="item.EOleveltitle"
              :value="item.EOlevelindex"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="SIM卡号：" class="wid50">
          <el-input
            v-model="form.SIMCARD_NO"
            placeholder="请输入SIM卡号"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="设备号：" class="wid50">
          <el-input
            v-model="form.IdentificationCode"
            placeholder="请输入设备号"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="载重："
          class="wid50"
          v-if="this.addDialogTitle === '新增车辆基础信息'"
        >
          <el-input
            v-model="form.WEIGHT"
            placeholder="请输入载重"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="isVisibleEdit = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import '@/assets/css/common.css'

import export2Excel from '@/utils/exportExcel/index.js'
import OSS from 'ali-oss';
import { time } from 'echarts';



export default {
  data () {

    return {
      clientData: [],
      currentPage: 1, //初始页
      pageSize: 10,    //    每页的数据
      originalData: [],
      tableData: [],
      selectClientInfoList: [],
      companyData: [],
      select: {
        LICENSE_PLATE: '',
        COMPANY: '',
      },
      isVisibleEdit: false,
      GPSlevel: [{
        GPSleveltitle: '未安装',
        GPSlevelindex: '0'
      }, {
        GPSleveltitle: '已安装',
        GPSlevelindex: '1'
      },],
      EOlevel: [{
        EOleveltitle: '未安装',
        EOlevelindex: '0'
      }, {
        EOleveltitle: '已安装',
        EOlevelindex: '1'
      },],
      form: {
      },
      addDialogTitle: '',
      showBigDialogVisible: false,
      srcBig: '',
      //图片上传
      fileList: [],
      VehicleUrl: '', //存上传后的车辆图片url
      CBPicUrl: '', //存上传后的车本图片url
      dataObj: {
        region: 'oss-cn-beijing',//我的存储是北京，可根据具体配置自行修改
        accessKeyId: 'LTAISI12uxTRFccz',
        accessKeySecret: 'cQAvLIZ9JizT5RXRNPBVcXfg3iURD8',
        bucket: 'photo-srw-hb2',
      }, //存签名信息
      baseAli: 'oss-cn-beijing.aliyuncs.com',
    }
  },
  // created () {
  //   if (localStorage.getItem('CTYPE') == '0') {
  //     this.rolelevel.shift()
  //   } else if (localStorage.getItem('CTYPE') != '-1') {
  //     this.rolelevel = []
  //   }
  // },
  mounted () {
    this.getcompanydata()
    this.getlistdata()
  },
  methods: {
    //获取公司列表
    async getcompanydata () {
      var url = 'Vehicle/GetCompanyInfoZT?ClientNO=0000&CompanyName=&Contacts=&Status=-1'
      const { data } = await this.$Http.get(url)
      this.companyData = data
    },
    //获取车辆列表
    async getlistdata () {
      var url = 'Vehicle/GetVehicleInfoZT?ClientNO=0000&CompanyName=&LicensePlate='
      const { data } = await this.$Http.get(url)
      data.forEach(element => {
        if (element.IsSetupGPS === '0') {
          element.GPSValue = '未安装'
        } else {
          element.GPSValue = '已安装'
        }
        if (element.VIDEO === '0') {
          element.EOValue = '未安装'
        } else {
          element.EOValue = '已安装'
        }
      });
      this.originalData = data
      this.screeningData()
    },
    change (e) {
      this.$forceUpdate()
    },
    // 导入Excel
    onChange (file, fileList) {
      //  console.log(fileList);
      this.fileData = file; // 保存当前选择文件
      this.readExcel(); // 调用读取数据的方法
    },
    // 读取数据
    readExcel (e) {
      let that = this;
      const files = that.fileData;
      console.log(files);
      if (!files) {
        //如果没有文件
        return false;
      } else if (!/\.(xls|xlsx)$/.test(files.name.toLowerCase())) {
        this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
        return false;
      }
      const fileReader = new FileReader();
      console.log(fileReader)
      fileReader.onload = ev => {
        try {
          const data = ev.target.result;
          //  console.log(ev.target)
          //  console.log(this);
          const workbook = this.XLSX.read(data, {
            type: "binary"// 以字符编码的方式解析
          });

          if (workbook.SheetNames.length >= 1) {
            //  this.$message({
            //    message: "导入数据表格成功",
            //    showClose: true,
            //    type: "success"
            //  });

            const wsname = workbook.SheetNames[0]; //取第一张表
            const ws = this.XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
            // console.log(ws)
            // this.inputExcelDataLength = ws.length
            // this.fullscreenLoading = this.$loading({
            //   lock: true,
            //   text: 'Loading',
            //   spinner: 'el-icon-loading',
            //   background: 'rgba(0, 0, 0, 0.7)'
            // })
            this.bulkLoad(ws)
          } else {
            this.$message.error("未读取到表格内容");
          }
        } catch (e) {
          return false;
        }
      };
      // 如果为原生 input 则应是 files[0]
      fileReader.readAsBinaryString(files.raw);
    },

    // 打开新增窗口
    handleAdd () {
      this.addDialogTitle = '新增车辆基础信息'
      //清空编辑框
      this.form = {
        LICENSE_PLATE: '',
        COMPANY: '',
        SIMCARD_NO: '',
        IdentificationCode: '',
        GPSValue: '0',
        EOValue: '0',
        WEIGHT: '',
      }
      //展示窗口
      this.isVisibleEdit = true;
      // this.idEdit = false;
    },
    // 打开编辑窗口
    handleEdit (index, row) {
      this.form = Object.assign({}, row);
      this.addDialogTitle = '编辑车辆基础信息'
      this.isVisibleEdit = true;
    },
    // 点击保存，判断是新增还是编辑操作
    handleSubmit () {
      if (this.addDialogTitle == '新增车辆基础信息') {
        this.saveAdd(this.form)
      } else {
        this.saveEdit()
      }
    },
    bulkLoad (ws) {
      ws.forEach(element => {
        var item = { IdentificationCode: '' }
        item.LICENSE_PLATE = element.车辆名称
        item.SIMCARD_NO = element.SIM卡号
        item.IdentificationCode = element.设备号
        item.WEIGHT = element.载重
        if (element.是否安装视频 === '已安装') {
          item.EOValue = 1
        } else {
          item.EOValue = 0
        }
        if (element.是否安装GPS === '已安装') {
          item.GPSValue = 1
        } else {
          item.GPSValue = 0
        }
        item.CID = this.companyData.filter(company => company.CompanyName === element.车辆所属公司)[0].CID
        Object.keys(item).forEach(key => {
          if (item[key] === undefined) {
            item[key] = ''
            console.log(item[key])
          }
        });
        this.saveAdd(item)
      });
    },
    // 新增保存
    async saveAdd (item) {
      var url = 'Vehicle/SaveVehicleInfoZT?VID=-1&LicensePlate=' + item.LICENSE_PLATE + '&CompanyID=' + item.CID + '&SIM=' + item.SIMCARD_NO +
        '&IdentificationCode=' + item.IdentificationCode + '&IsSetupGPS=' + item.GPSValue + '&VIDEO=' + item.EOValue + '&WEIGHT=' + item.WEIGHT
      const { data } = await this.$Http.get(url)
      if (data.IsSucess) {
        this.$message.success('新增成功');
        this.isVisibleEdit = false
        this.getlistdata()
      } else {
        this.$message.error('新增失败');
      }

    },
    // 保存编辑
    async saveEdit () {
      let CompanyValue = ''
      CompanyValue = this.companyData.filter(item => item.CompanyName === this.form.COMPANY)[0].CID
      const params = {
        VID: this.form.VID,
        LicensePlate: this.form.LICENSE_PLATE,
        CompanyID: this.form.CID,
        SIM: this.form.SIMCARD_NO,
        IdentificationCode: this.form.IdentificationCode,
        IsSetupGPS: this.form.IsSetupGPS,
        VIDEO: this.form.VIDEO,
        WEIGHT: this.form.WEIGHT,
      }
      const { data } = await this.$Http.get('Vehicle/SaveVehicleInfoZT', { params })
      if (data.IsSucess) {
        this.$message.success('编辑成功');
        this.isVisibleEdit = false
        this.getlistdata()
      } else {
        this.$message.error('编辑失败');
      }
    },
    // 删除车辆信息
    async handleDelete (index, row) {
      const confirmResult = await this.$confirm('确定删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult == 'confirm') {
        const params = {
          ID: row.ID,
        }
        const { data } = await this.$Http.get('CarService/DeleteCarInformationInfo', { params })
        if (data.IsSucess) {
          this.$message.success('删除成功')
          this.isVisibleEdit = false
          this.getlistdata()
        } else {
          this.$message.error('删除失败');
        }
      } else {
        this.$message.info('取消删除')
        this.isVisibleEdit = false
      }

    },
    // 模糊查询
    screeningData () {
      this.currentPage = 1;
      this.tableData = this.originalData
      if (this.select.LICENSE_PLATE) this.tableData = this.tableData.filter(item => item.LICENSE_PLATE.includes(this.select.LICENSE_PLATE))
      if (this.select.COMPANY) this.tableData = this.tableData.filter(item => item.COMPANY.includes(this.select.COMPANY))
      console.log(this.select.name)
    },
    // 导出Excel
    exportExcel () {
      let excelName = '车辆基础信息'
      const tHeader = ['ID', '车辆所属公司', '车辆名称', '车辆类型', '是否安装GPS', 'SIM卡号', '是否安装视频', '设备号', '载重']
      const filterVal = ['VID', 'COMPANY', 'LICENSE_PLATE ', 'CAR_TYPE', 'GPSValue', 'SIMCARD_NO', 'EOValue', 'IdentificationCode', 'WEIGHT']
      export2Excel(tHeader, filterVal, this.tableData, excelName)
    },
    // 分页导航
    handlePageChange (currentPage) {
      this.currentPage = currentPage;
      // console.log(this.currentPage)
      // this.$set(this.query, 'pageIndex', val);
      // this.getlistdata();
    },
    handleSizeChange (size) {
      this.pageSize = size;
      console.log(this.pageSize)
    }
  }
}
</script>
<style>
.content {
  overflow-y: scroll;
}
.el-col-6 {
  min-width: 400px;
  min-height: 50px;
}
.el-table th {
  height: 40px;
}
.el-form-item label {
  width: 80px;
}
/* .el-upload--text {
  width: 300px;
} */
</style>